
// npm i passport passport-jwt jsonwebtoken
import { injectable } from "inversify";
import passport from "passport";
import jsonwebtoken from "jsonwebtoken";
import { Strategy,ExtractJwt } from "passport-jwt"; //passport的插件

@injectable()
export class JWT{
    private secretKey:string = "secret";// 秘钥
    private jwtOptions:any = {
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
        secretOrKey: this.secretKey
    };
    constructor(){
        this.strategy(); // 在构造函数中注册策略
    }

    strategy(){
        let str = new Strategy(this.jwtOptions,(payload, done)=>{
            done(null, payload);
        })

        passport.use(str);//得passport注册插件
    }

    static middleware(){
        // 经过中间件验证token
        return passport.authenticate("jwt", { session: false });
    }

    /**
     * 生成token
     */
    public createToken(data:Object){
        return jsonwebtoken.sign(data, this.secretKey, { expiresIn: "1h" });
    }

    /**
     * 关联express
     */
    public init(){
        return passport.initialize();
    }
}